let activeReactiveFn = null
class Depend {
    constructor() {
        this.reactiveFns = new Set();
    }
    depend() {
        if (activeReactiveFn) {
            this.reactiveFns.add(activeReactiveFn)
        }
    }
    notify() {
        this.reactiveFns.forEach(fn => {
            fn()
        })
    }
}


function watchFn(fn) {
    activeReactiveFn = fn
    fn();
    activeReactiveFn = null
}
const targetMap = new WeakMap()
const getDepend = function (target, key) {
    let map = targetMap.get(target);
    if (!map) {
        map = new Map()
        targetMap.set(target, map)
    }
    let depend = map.get(key)
    if (!depend) {
        depend = new Depend();
        map.set(key, depend)
    }
    return depend
}


function reactive(obj) {
    return new Proxy(obj, {
        get(target, key, receiver) {
            const depend = getDepend(target, key)
            depend.depend()
            return Reflect.get(target, key, receiver)
        },
        set(target, key, newValue, receiver) {
            Reflect.set(target, key, newValue, receiver)
            const depend = getDepend(target, key)
            depend.notify() //属性一改变就触发
        }
    })
}

// 监听对象的属性变量: Proxy(vue3)/Object.defineProperty(vue2)
const objProxy = reactive({
    name: "why", // depend对象
    age: 18 // depend对象
})

const infoProxy = reactive({
    address: "广州市",
    height: 1.88
})

watchFn(() => {
    console.log(infoProxy.address, '地址值');
})

infoProxy.address = "北京市"

const foo = reactive({
    name: "foo"
})

watchFn(() => {
    console.log(foo.name, 'name名字')
})

foo.name = "bar"
